package org.pzy.rocketmq;

import org.apache.rocketmq.client.apis.ClientConfiguration;
import org.apache.rocketmq.client.apis.ClientConfigurationBuilder;
import org.apache.rocketmq.client.apis.ClientException;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.message.Message;
import org.apache.rocketmq.client.apis.producer.Producer;
import org.apache.rocketmq.client.apis.producer.SendReceipt;

/**
 * @Author: DRevelation
 * @Date: 2022/11/3 13:47
 * todo 测试未通过（用rocketmq 4.x也不行）
 * rocketmq 5.0需要配置proxy https://blog.csdn.net/weixin_43982927/article/details/131219187
 * fixed 20240320 测试通过 https://github.com/apache/rocketmq/issues/7508 延迟消息时需要手动（命令，proxy模式代码不能自动创建）建立topic消息类型，dashboard只能建普通消息
 */
public class ProducerExample {
    public static void main(String[] args) throws ClientException {
        //接入点地址，需要设置成Proxy的地址和端口列表，一般是xxx:8081;xxx:8081。
        String endpoint = "192.168.56.101:8081";
        //消息发送的目标Topic名称，需要提前创建
        //$ sh bin/mqadmin updatetopic -n localhost:9876 -t TestTopic
        String topic = "Topic-20240320";

        ClientServiceProvider provider = ClientServiceProvider.loadService();
        ClientConfigurationBuilder builder = ClientConfiguration.newBuilder().setEndpoints(endpoint);
        ClientConfiguration configuration = builder.build();

        Producer producer = provider.newProducerBuilder()
                .setTopics(topic)
                .setClientConfiguration(configuration)
                .build();

        Message message = provider.newMessageBuilder()
                .setTopic(topic)
                .setKeys("messageKey")
                .setTag("messageTag")
                .setDeliveryTimestamp(System.currentTimeMillis() + 3600) // 延时消息设置
                .setBody("messageBody".getBytes())
                .build();

        try {
            SendReceipt sendReceipt = producer.send(message);
            System.out.println(sendReceipt.getMessageId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
